import { _decorator, Component, Node, SpriteFrame,Sprite, Label, color, RichText } from 'cc';
import { ResourceManager } from '../Core/ResourceManager';
import { PicPath } from '../Config/ResourceConfig';
import { Core } from '../Core/Core';
import { SkillConfig } from '../Config/SkillConfig';
import { EColor, EEvent, ESkill } from '../Config/Enum';
const { ccclass, property } = _decorator;

@ccclass('RuneManager')
export class RuneManager extends Component {
    //节点
    ndIcon: Node = null;
    spIcon: SpriteFrame = null;
    ndRuneBoard: Node = null;
    runeName_lowerCase: string = "";
    runeId: number = 0; // 符文ID
    //ndBorder   : Node = null; // 符文选择框
    //runeName_Uppcase: string = ""; // 符文名称大写形式
    ndBG: Node = null; // 符文背景
    skill
    ndMask


    

    protected onLoad(): void {
        //
        this.ndBG = this.node.getChildByName('BG'); // 符文选择框
        this.ndMask = this.node.getChildByName('Mask'); // 符文遮罩
        console.log("RuneManager onLoad,Core.Instance.currentPlayer:", Core.Instance.currentPlayer);
        console.log("RuneManager onLoad ,Core.Instance.currentSkill:", Core.Instance.currentSkill);
        //this.runeName_Uppcase = this.node.name; // 假设节点名称是 "Rune1", "Rune2", "Rune3" 等














        
    }

    protected onEnable(): void {

        this.runeId = parseInt(this.node.name.slice(-1)); // 假设节点名称是 "Rune1", "Rune2", "Rune3" 等
        this.runeName_lowerCase = this.node.name.charAt(0).toLowerCase() + this.node.name.slice(1);; // Rune1 -> rune1
        
        this.skill = Core.Instance.players.get(Core.Instance.currentPlayer).skillData.skills.get(Core.Instance.currentSkill as ESkill); // 获取当前武学对象

                // 展示符文图标
        //this.node.getChildByName('Icon').getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[Core.Instance.currentSkill+this.node.name])
        ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[Core.Instance.currentSkill+this.node.name]+"/spriteFrame")
        .then((spriteFrame) => {
            this.node.getChildByName('Icon').getComponent(Sprite).spriteFrame = spriteFrame;
        })
        .catch((error) => {
            console.error("加载符文图标失败:", error);
        });

        // 展示符文Desc
        //this.node.getChildByName('Desc').getComponent(RichText).string = SkillConfig[Core.Instance.currentSkill]["rune"+this.runeId] || "无描述";

        // 展示符文Desc - 使用富文本格式化
        const runeDesc = SkillConfig[Core.Instance.currentSkill]["rune"+this.runeId] || "无描述";
        this.node.getChildByName('Desc').getComponent(RichText).string = this.formatRuneDescription(runeDesc);

        this.isChecked(); // 检查当前符文是否已被选中

        this.onSkillUpgrade();
        this.node.on(Node.EventType.TOUCH_END, this.onBtnChooseRune, this);
        Core.Instance.event.on(EEvent.SkillUpgrade, this.onSkillUpgrade, this)  

        // // 如果选择的符文是自己，则让this.node.getComponent(Sprite).color = color().fromHEX(EColor.Orange_Light); // 设置当前符文的颜色为绿色，要不就透明
        // if (Core.Instance.players.get(Core.Instance.currentPlayer).skillData.skills.get(Core.Instance.currentSkill as ESkill).runeId === this.runeId) {
        //     this.node.getComponent(Sprite).color = color().fromHEX(EColor.Orange_Light); // 设置当前符文的颜色为绿色
        //     //this.ndBorder.active = true; // 显示当前符文的边框
        // } else {
        //     this.node.getComponent(Sprite).color = color().fromHEX(EColor.White); // 设置当前符文的颜色为白色
        //     //this.ndBorder.active = false; // 隐藏当前符文的边框
        // }

        
    }

        // 新增：格式化符文描述的方法
        private formatRuneDescription(desc: string): string {
            // 分离符文名称和描述（假设格式是 "名称: 描述"）
            const colonIndex = desc.indexOf(':');
            if (colonIndex !== -1) {
                const name = desc.substring(0, colonIndex);
                const description = desc.substring(colonIndex + 1);
                return `<color=#FFFF00>${name}:</color>${description}`;
            }
            
            // 如果没有冒号，直接返回原描述
            return desc;
        }

    protected onDisable(): void {
        this.node.off(Node.EventType.TOUCH_END, this.onBtnChooseRune, this); 
        Core.Instance.event.off(EEvent.SkillUpgrade, this.onSkillUpgrade, this)  
    }

    start() {

    }

    update(deltaTime: number) {
        
    }

    isChecked() {
        // 如果选择的符文是自己，则让this.ndBG.active = true; // 显示当前符文的边框
        if (Core.Instance.players.get(Core.Instance.currentPlayer).skillData.skills.get(Core.Instance.currentSkill as ESkill).runeId === this.runeId) {
            this.ndBG.active = true; // 显示当前符文的边框

        } else {
            this.ndBG.active = false; // 隐藏当前符文的边框

        }
    }    


    onSkillUpgrade(){
        console.log("rune:", this.skill);
        this.ndMask.active = true

        switch (this.node.name) {
            case "Rune1":

                if(this.skill.level >= 3){
                    console.log("Rune1 skill", this.skill);  
                    console.log("Rune1 skill.level", this.skill.level);
                    this.ndMask.active = false; // 符文遮罩
                }
                break;
            case "Rune2":

                if(this.skill.level >= 6){
                    console.log("Rune2 skill", this.skill);  
                    console.log("Rune2 skill.level", this.skill.level);
                    this.ndMask.active = false; // 符文遮罩
                }
                break;
            case "Rune3":
                if(this.skill.level >= 9){
                    console.log("Rune3 skill", this.skill);  
                    console.log("Rune3 skill.level", this.skill.level);
                    this.ndMask.active = false; // 符文遮罩
                }
                break;
            default:
                console.error("未知武学类型:", Core.Instance.currentSkill);
        }

    }
    onBtnChooseRune() {
        console.log("点击了符文按钮", this.node.name);
        console.log("当前符文ID:", this.runeId, "当前武学:", Core.Instance.currentSkill);
        // // 检查当前符文是否已被选中
        // if (Core.Instance.currentRune === this.runeName) {
        //     console.log("当前符文已被选中，取消选择");
        //     Core.Instance.currentRune = ""; // 取消选择
        // } else {
        //     console.log("选择了新的符文:", this.runeName);
        //     Core.Instance.currentRune = this.runeName; // 选择新的符文
        // }
        
        // Core.Instance.event.emit('RuneSelected', this.runeName); // 触发事件通知其他组件

        Core.Instance.players.get(Core.Instance.currentPlayer).skillData.skills.get(Core.Instance.currentSkill as ESkill).runeId = this.runeId; // 设置当前武学的符文
        // 让自己的边框显现，让其他符文边框消失
        this.ndBG.active = true; // 显示当前符文的边框
        //this.node.getComponent(Sprite).color = color().fromHEX(EColor.Orange_Light); // 设置当前符文的颜色为绿色

        for (let rune of this.node.parent.children) {
            if (rune.name !== this.node.name) {
                rune.getChildByName('BG').active = false; // 隐藏其他符文的边框
            }
        }

        Core.Instance.save(); // 保存数据
        Core.Instance.event.emit(EEvent.SkillUpgrade); // 触发符文更换事件






    }
}


